#-*- coding:utf-8 -*-
import time
from datetime import * 
from django.http import HttpResponse,HttpResponseRedirect
from django.contrib import auth
from django.core.context_processors import csrf
from django import forms
from django.contrib.auth.forms import UserCreationForm
from django.template import Context, loader
from django.template import RequestContext
from django.http import Http404
from django.shortcuts import render_to_response,get_object_or_404,render,get_list_or_404,redirect
from django.core.urlresolvers import reverse
from util.util import *
from django.core.paginator import Paginator, EmptyPage, PageNotAnInteger
from models import *


from tastypie.http import HttpUnauthorized, HttpForbidden
from tastypie.models import ApiKey, create_api_key
from tastypie.resources import ModelResource
from tastypie.utils import trailing_slash


from util.estimate import estimateTime
from util.googlemaps1 import GoogleMaps
api_key = 'ABQIAAAAevysxt9O5lBUCrSalm80MxQx8gmx0K-_Fjj4Tf8bNXH3BBSxZRRmI_CuZM2zQyuXEpG_uxt-aqPr-A'
gmaps = GoogleMaps(api_key)

def index(request):
    return render_to_response('index.html')
    #return redirect("http://www.baidu.com")

def formatDate(dateStr):
    print datetime.now()
    if dateStr == '':
        return datetime.now()
    if (len(dateStr) == len('01/01/2013 00:00')):
        return datetime.strptime(str(dateStr), '%m/%d/%Y %H:%M')
    if (len(dateStr) == len('01/01/2013 00:00:00')):
        return datetime.strptime(str(dateStr), '%m/%d/%Y %H:%M:%S')

def GenerateSchedule():
    Schedule.objects.all().delete()
    now = datetime.now()
    start_date = now - + timedelta(days = 10)
    end_date = now + timedelta(days = 10)
    query_set = Event.objects.filter(end_date_time__range=(start_date, end_date))
    event_list = list(query_set)
    updateUserSchedule(event_list)


def addEvent(request):
    modelresource = ModelResource()
    data = modelresource.deserialize(request, request.body, format=request.META.get('CONTENT_TYPE', 'application/json'))
    event = Event()
    #now = datetime.now()
    event.event_name = data.get("title", "event_title")
    event.start_date_time = formatDate(data.get("start_time", ""))
    event.end_date_time =  formatDate(data.get("end_time", ""))
    # #timedelta([days[, seconds[, microseconds[, milliseconds[, minutes[, hours[, weeks]]]]]]])
    event.duration_minutes = data.get("time_cost", 60)
    event.start_addr = data.get("location", "")
    event.end_addr = data.get("location", "")
    event.important_lever = data.get("importance", 3)
    event. weather_lever = data.get("sensitive_to_weather", 3)
    event.save()
    
    GenerateSchedule()

    return modelresource.create_response(request, {
        'success' : True,
        'id' : event.id,
    })

def updateEvent(request):
    modelresource = ModelResource()
    data = modelresource.deserialize(request, request.body, format=request.META.get('CONTENT_TYPE', 'application/json'))
    event_id = data.get('id')
    print event_id
    event = Event.objects.get(pk = event_id)
    event.event_name = data.get("title", "event_title")
    event.start_date_time = formatDate(data.get("start_time", ""))
    event.end_date_time =  formatDate(data.get("end_time", ""))
    # #timedelta([days[, seconds[, microseconds[, milliseconds[, minutes[, hours[, weeks]]]]]]])
    event.duration_minutes = data.get("time_cost", 60)
    event.start_addr = data.get("location", "")
    event.end_addr = data.get("location", "")
    event.important_lever = data.get("importance", 3)
    event. weather_lever = data.get("sensitive_to_weather", 3)
    event.save()

    GenerateSchedule()

    return modelresource.create_response(request, {
        'success' : True,
        'id' : event_id,
    })

def deleteEvent(request):
    modelresource = ModelResource()
    data = modelresource.deserialize(request, request.body, format=request.META.get('CONTENT_TYPE', 'application/json'))
    event_id = data.get('id')
    Event.objects.get(pk = event_id).delete()
    return modelresource.create_response(request, {
        'success' : True,
        'id' : event_id,
    })

def getEventList(request):
    modelresource = ModelResource()
    data = modelresource.deserialize(request, request.body, format=request.META.get('CONTENT_TYPE', 'application/json')) 
    event_list = list(Event.objects.all())
    josn_list = []
    for event in event_list:
        event_josn = {
        'id' : event.id,
        'title' : event.event_name,
        'start_time' : event.start_date_time.strftime('%m/%d/%Y %H:%M:%S'),
        'end_time' : event.end_date_time.strftime('%m/%d/%Y %H:%M:%S'),
        'location' : event.end_addr,
        'time_cost' : event.duration_minutes,
        'importance' : event.important_lever,
        'sensitive_to_weather' : event. weather_lever,
        }
        josn_list.append(event_josn)
    return modelresource.create_response(request, {
        'success' : True,
        'eventList' : josn_list,
    })

def getScheduleList(request):
    modelresource = ModelResource()
    data = modelresource.deserialize(request, request.body, format=request.META.get('CONTENT_TYPE', 'application/json'))
    schedule_list = list(Schedule.objects.all())
    josn_list = []
    for schedule in schedule_list:
        schedule_josn = {
        'id' : schedule.id,
        'title' : schedule.event_name,
        'start_time' : schedule.start_date_time.strftime('%m/%d/%Y %H:%M:%S'),
        'end_time' : schedule.end_date_time.strftime('%m/%d/%Y %H:%M:%S'),
        'location' : schedule.end_addr
        # 'time_cost' : event.duration_minutes,
        # 'importance' : event.important_lever,
        }
        josn_list.append(schedule_josn)

    return modelresource.create_response(request, {
        'success' : True,
        'scheduleList' : josn_list,
    })

def updateUserSchedule(raw_event_list):

    for event in raw_event_list:
        event.value = 100
    raw_event_list.sort(cmp = my_cmp)
    today = datetime.now()
    #greedySchedule(raw_event_list, schedule_list, today.strftime("%Y-%m-%d"))
    # return True
    schedule_dict = {}
    for key in range(CONSTANT_SCHEDULE_DAYS):
        schedule_dict[str(key)] = []

    getScheduleDict(raw_event_list, schedule_dict,)
    print schedule_dict
    #event_list = []
    for step in range(CONSTANT_SCHEDULE_DAYS):
        print 'updateUserSchedule: step = ' + str(step)
        schedule_list=[]
        event_list = greedySchedule(schedule_dict[str(step)],schedule_list,(today + timedelta(days=step)).strftime("%Y-%m-%d"))
        for schedule in schedule_list:
            schedule.save()
        getScheduleDict(event_list, schedule_dict, step)

def greedySchedule(event_list, schedule_list, date):
    event_left = []
    system_end_time = time(0,0,0)
    last_end_time = None
    start_addr, end_addr = '', ''
    for event in event_list: 
        if event.start_date_time.strftime('%Y-%m-%d') > str(date):
            event_left.append(event)
            continue
        if last_end_time == None:
            last_end_time = time(event.start_date_time.hour, event.start_date_time.minute,event.start_date_time.second)
            start_addr, end_addr = event.start_addr, event.start_addr
        else:
            end_addr = event.end_addr

        #start_addr = '闵行'
        #end_addr = '上海市徐汇区'
        transport = 'h' # tranport: h避免高速公路, t避免收费路段, r采用公共交通, w步行方式, b骑行方式
        #directions = gmaps.directions(startAdress, destination, transport)
        #distance_min = estimateTime(start_addr,end_addr,transport,True)
        distance_min = 0
        #update event start_date_time
        event.start_date_time = datetime.strptime(str(event.start_date_time.date()) + ' ' + str(last_end_time.hour) + ':' + str(last_end_time.minute), '%Y-%m-%d %H:%M')
        print event.start_date_time
        for k in range(1,100):
            cur_start_time = event.start_date_time + timedelta(minutes = (event.duration_minutes * (k - 1) + distance_min))
            cur_end_time = event.start_date_time + timedelta(minutes = (event.duration_minutes * k))
            if cur_end_time.strftime('%H:%M') > event.end_date_time.strftime('%H:%M'):
                event_left.append(event)
                break
            if cur_start_time.strftime('%H:%M') >= last_end_time.strftime('%H:%M'):
                last_end_time = time(cur_end_time.hour, cur_end_time.minute, cur_end_time.second)
                start_addr = event.end_addr
                schedule = Schedule()
                schedule.event_name = event.event_name
                schedule.start_date_time = datetime.strptime(str(date) + ' ' + cur_start_time.strftime('%H:%M'), '%Y-%m-%d %H:%M')
                schedule.end_date_time = datetime.strptime(str(date) + ' ' + cur_end_time.strftime('%H:%M'), '%Y-%m-%d %H:%M')
                schedule.start_addr = event.start_addr
                schedule.end_addr = event.end_addr
                schedule_list.append(schedule)
                print event.event_name,cur_start_time.strftime('%H:%M'),cur_end_time.strftime('%H:%M')
                break;
    return event_left

